package com.starblink.login.accountmanagement.ui

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.basic.apollo.ext.ApolloExt.findErrorCode
import com.starblink.android.basic.ext.ApolloModelExt.getThirdLoginInfo
import com.starblink.basic.apollo.ext.ApolloValSetExt
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.network.base.BaseApiCodeAndUrl
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.user.login.FacebookLoginUtils
import com.starblink.android.basic.user.login.GoogleLoginUtils
import com.starblink.android.basic.user.login.LoginManager
import com.starblink.rocketreserver.BindingThirdAccountMutation
import com.starblink.rocketreserver.FetchAccountInfoQuery
import com.starblink.rocketreserver.UnbindingThirdAccountMutation
import com.starblink.rocketreserver.type.LoginChannel
import kotlinx.coroutines.launch

class AccountManagementVM : BaseViewModel() {
    var bindFacebook = false // true表示已绑定Facebook账号
    var bindGoogle = false // true表示已绑定Google账号

    val unbindThirdLoginResLiveData: MutableLiveData<Pair<LoginChannel, Boolean>> =
        MutableLiveData()
    val bindThirdLoginResLiveData: MutableLiveData<Pair<LoginChannel, BindThirdState>> =
        MutableLiveData()

    /**
     * 绑定三方登录账号
     */
    fun bindThirdLogin(
        loginChannel: LoginChannel,
        accessToken: String,
        authorizationCode: String = ""
    ) {
        viewModelScope.launch {
            val response = SkGqlClient.skMutation(
                BindingThirdAccountMutation(
                    channel = loginChannel,
                    thirdToken = accessToken,
                    authorizationCode = authorizationCode
                ),
                showDefaultLoading = true
            )
            if (response?.data != null) {
                if (response.data!!.bindingThirdAccount) {
                    // 绑定成功，更新状态
                    if (loginChannel == LoginChannel.google) {
                        bindGoogle = true
                        val refreshRes = LoginManager.refreshUserInfo().await()
                    } else {
                        // facebook登录
                        bindFacebook = true
                        val refreshRes = LoginManager.refreshUserInfo().await()
                    }
                    toast(com.starblink.basic.style.R.string.connect_success)
                    bindThirdLoginResLiveData.postValue(Pair(loginChannel, BindThirdState.SUCCESS))
                } else {
                    // 绑定失败
                    toast(com.starblink.basic.style.R.string.connect_fail2)
                    bindThirdLoginResLiveData.postValue(Pair(loginChannel, BindThirdState.FAIL))
                }
            } else if (response?.errors != null) {
                if(response.findErrorCode(BaseApiCodeAndUrl.ACCOUNT_00012)){
                    //三方账号已绑定其他Guang账号，弹窗提示用户
                    bindThirdLoginResLiveData.postValue(
                        Pair(
                            loginChannel,
                            BindThirdState.BOUND
                        )
                    )
                }
            }
        }
    }

    enum class BindThirdState {
        SUCCESS,
        FAIL,
        BOUND // 三方账号已绑定
    }

    /**
     * 解绑三方登录账号
     */
    fun unbindThirdLogin(loginChannel: LoginChannel) {
        viewModelScope.launch {
            var id: String
            if (loginChannel == LoginChannel.google) {
                // googleLoginInfo或facebookLoginInfo可能为空，绑定三方登录账号后，如果加载用户信息失败，则为空
                var googleLoginInfo =
                    UserDataCenter.getAccountInfo()?.getThirdLoginInfo(LoginChannel.google)
                if (googleLoginInfo == null) {
                    // 如果googleLoginInfo == null，重新刷新用户信息
                    val refreshRes = LoginManager.refreshUserInfo().await()
                    if (refreshRes == null) {
                        toast(com.starblink.basic.style.R.string.disconnect_fail)
                        return@launch
                    } else {
                        googleLoginInfo = refreshRes.getThirdLoginInfo(LoginChannel.google)
                    }
                }
                id = googleLoginInfo?.id ?: ""
            } else {
                var facebookLoginInfo =
                    UserDataCenter.getAccountInfo()?.getThirdLoginInfo(LoginChannel.facebook)
                if (facebookLoginInfo == null) {
                    val refreshRes = LoginManager.refreshUserInfo().await()
                    if (refreshRes == null) {
                        toast(com.starblink.basic.style.R.string.disconnect_fail)
                        return@launch
                    } else {
                        facebookLoginInfo = refreshRes.getThirdLoginInfo(LoginChannel.facebook)
                    }
                }
                id = facebookLoginInfo?.id ?: ""
            }
            val response = SkGqlClient.skMutation(
                UnbindingThirdAccountMutation(
                    id = id
                ),
                showDefaultLoading = true
            )
            if (response?.data != null) {
                if (response.data!!.unbindingThirdAccount) {
                    // 解绑成功，更新状态，更新用户数据，toast提示，postValue
                    if (loginChannel == LoginChannel.google) {
                        bindGoogle = false
                        // 移除用户数据中的谷歌登录信息
                        removeThirdLoginInfo(LoginChannel.google)
                        GoogleLoginUtils.revokeAccess()
                    } else {
                        bindFacebook = false
                        // 移除用户数据中的脸书登录信息
                        removeThirdLoginInfo(LoginChannel.facebook)
                        FacebookLoginUtils.signOut()
                    }
                    toast(com.starblink.basic.style.R.string.disconnect_success)
                    unbindThirdLoginResLiveData.postValue(
                        Pair(
                            loginChannel,
                            response.data!!.unbindingThirdAccount
                        )
                    )
                } else {
                    // 解绑失败
                    toast(com.starblink.basic.style.R.string.disconnect_fail)
                }
            }
        }
    }

    /**
     * 移除用户数据中指定的三方登录信息
     */
    private fun removeThirdLoginInfo(loginChannel: LoginChannel) {
        UserDataCenter.getAccountInfo()?.let { accountInfo ->
            accountInfo.thirdList?.filter {
                it.loginType != if (loginChannel == LoginChannel.google) LoginManager.THIRD_LOGIN_GOOGLE
                else LoginManager.THIRD_LOGIN_FACEBOOK
            }?.let {
                ApolloValSetExt.setApolloVal<FetchAccountInfoQuery.FetchAccountInfo>(
                    model = accountInfo,
                    declaredField = "thirdList",
                    value = it
                )
                UserDataCenter.setAccountInfo(accountInfo)
            }
        }
    }
}